import React, { useState, useEffect } from 'react';
import { Spin, Tree, Input } from 'antd';
import { AxTreeProps } from './data';
import styles from './style.less';
import { TreeProps } from 'antd/lib/tree';
import { axhelper } from '@/shared/axhelper';

const { TreeNode } = Tree;
const { Search } = Input;
const getTreeDataList = (d: any) => {
    let l: any = [];
    d.map((i: any) => {
        l.push({ key: i.key, title: i.title });
        if (i.children) l.push(...getTreeDataList(i.children));
    });
    return l;
}
const loop = (data: any, searchValue: any): any => data.map((item: any) => {
    const index = item.title.indexOf(searchValue);
    const beforeStr = item.title.substr(0, index);
    const afterStr = item.title.substr(index + searchValue.length);
    const title =
        index > -1 ? (
            <span>
                {beforeStr}
                <span style={{ color: '#f50' }}>{searchValue}</span>
                {afterStr}
            </span>
        ) : (
                <span>{item.title}</span>
            );
    if (item.children) {
        return (
            <TreeNode key={item.key} title={title} titleText={item.title} extraId={item.extraId} >
                {loop(item.children, searchValue)}
            </TreeNode>
        );
    }
    return <TreeNode key={item.key} title={title} titleText={item.title} extraId={item.extraId} />;
});


const AxTree: React.FC<AxTreeProps & Omit<TreeProps, 'treeData' | 'selectable'>> = props => {
    const { handleRead, expandAll = false, showSearch = true, selectable, extraId,
        searchPlaceholder = '请输入搜索内容', ...rest } = props;
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [loading, setLoading] = useState(false);
    const [treeData, setTreeData] = useState<any>([]);
    /** 将所有节点都放在一个列表中 */
    const [treeDataList, setTreeDataList] = useState<any>([]);
    const [searchValue, setSearchValue] = useState<any>('');
    /** 是否自动展开父节点（不能定义初始值） */
    const [autoExpandParent, setAutoExpandParent] = useState<any>();

    useEffect(() => {
        if (handleRead) {
            setLoading(true);
            handleRead().then((res: any) => {
                const d = axhelper.transToTreeData(res.list, selectable, null, { extraId: extraId });
                const list = getTreeDataList(d);

                /** 展开树 */
                if (expandAll && expandedKeys.length === 0) {
                    setExpandedKeys(list.map((i: any) => i.key));
                }
                setTreeData(d);
                setTreeDataList(list);
            }).finally(() => {
                setLoading(false);
            });
        }
    }, []);

    const handleExpand = (keys: any) => {
        setExpandedKeys(keys);
        setAutoExpandParent(false);
    }

    const getParentKey = (key: any, tree: any) => {
        let parentKey: any;
        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];
            if (node.children) {
                if (node.children.some((item: any) => item.key === key)) {
                    parentKey = node.key;
                } else if (getParentKey(key, node.children)) {
                    parentKey = getParentKey(key, node.children);
                }
            }
        }
        return parentKey;
    }

    const handleChange = (e: any) => {
        const value = e.target.value.trim();
        const expandedKeys = treeDataList
            .map((item: any) => {
                if (item.title.indexOf(value) > -1) {
                    return getParentKey(item.key, treeData);
                }
                return null;
            })
            .filter((item: any, i: any, self: any) => item && self.indexOf(item) === i);
        setExpandedKeys(expandedKeys);
        setSearchValue(value);
        setAutoExpandParent(true);
    }

    return (
        <>
            {showSearch && <Search
                placeholder={searchPlaceholder}
                onChange={handleChange}
                style={{ marginBottom: 2 }}
                allowClear
            />}
            <Tree
                // treeData={treeData}
                onExpand={handleExpand}
                expandedKeys={expandedKeys}
                autoExpandParent={autoExpandParent}
                {...rest}
            >
                {loop(treeData, searchValue)}
            </Tree>
            {loading && (
                <div className={styles.axLoadingContainer}>
                    <Spin />
                </div>
            )}
        </>
    );
}

export default AxTree;
